"""简易抽奖系统

实现一个简单的抽奖系统，支持：
1. 参与者名单管理（从文件读取或手动输入）
2. 抽奖规则设置（奖项和获奖人数）
3. 随机抽取功能
4. 结果输出和保存
"""

import random
from typing import List, Dict
from datetime import datetime


class LotterySystem:
    def __init__(self):
        """初始化抽奖系统"""
        self.participants = []  # 参与者名单
        self.prizes = {}  # 奖项设置：{奖项名: 获奖人数}
        self.winners = {}  # 获奖结果：{奖项名: [获奖者名单]}
        
    def add_participant(self, name: str) -> None:
        """添加单个参与者"""
        if name and name not in self.participants:
            self.participants.append(name)
            
    def add_participants_from_file(self, file_path: str) -> None:
        """从文件中批量导入参与者名单"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    name = line.strip()
                    if name:
                        self.add_participant(name)
        except FileNotFoundError:
            print(f"错误：找不到文件 {file_path}")
        except Exception as e:
            print(f"错误：读取文件时发生错误 - {str(e)}")
            
    def set_prize(self, prize_name: str, winner_count: int) -> None:
        """设置奖项和对应的获奖人数"""
        if winner_count > 0:
            self.prizes[prize_name] = winner_count
            
    def draw_lottery(self, prize_name: str) -> List[str]:
        """进行抽奖"""
        if prize_name not in self.prizes:
            print(f"错误：未找到奖项 {prize_name}")
            return []
            
        # 获取当前奖项需要抽取的人数
        winner_count = self.prizes[prize_name]
        
        # 获取可参与抽奖的人员（排除已中奖者）
        available_participants = [p for p in self.participants 
                                if not any(p in w for w in self.winners.values())]
        
        if len(available_participants) < winner_count:
            print(f"警告：可参与抽奖的人数不足！需要{winner_count}人，当前仅有{len(available_participants)}人")
            return []
            
        # 随机抽取指定数量的获奖者
        winners = random.sample(available_participants, winner_count)
        self.winners[prize_name] = winners
        return winners
    
    def save_results(self, file_path: str) -> None:
        """保存抽奖结果到文件"""
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(f"抽奖结果 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write("=" * 50 + "\n")
                for prize_name, winners in self.winners.items():
                    f.write(f"\n{prize_name}：\n")
                    for i, winner in enumerate(winners, 1):
                        f.write(f"{i}. {winner}\n")
                f.write("\n" + "=" * 50)
        except Exception as e:
            print(f"错误：保存结果时发生错误 - {str(e)}")
    
    def display_results(self) -> None:
        """显示抽奖结果"""
        if not self.winners:
            print("\n还未进行抽奖！")
            return
            
        print("\n抽奖结果：")
        print("=" * 50)
        for prize_name, winners in self.winners.items():
            print(f"\n{prize_name}：")
            for i, winner in enumerate(winners, 1):
                print(f"{i}. {winner}")
        print("\n" + "=" * 50)


def main():
    # 创建抽奖系统实例
    lottery = LotterySystem()
    
    # 示例：添加参与者
    participants = ["张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十"]
    for participant in participants:
        lottery.add_participant(participant)
    
    # 设置奖项
    lottery.set_prize("一等奖", 1)
    lottery.set_prize("二等奖", 2)
    lottery.set_prize("三等奖", 3)
    
    # 进行抽奖
    print("\n开始抽奖...")
    for prize_name in ["三等奖", "二等奖", "一等奖"]:
        winners = lottery.draw_lottery(prize_name)
        if winners:
            print(f"\n{prize_name}获奖者：{', '.join(winners)}")
    
    # 显示完整结果
    lottery.display_results()
    
    # 保存结果
    lottery.save_results("lottery_results.txt")
    print("\n抽奖结果已保存到 lottery_results.txt")


if __name__ == "__main__":
    main()
